//
//  HMOAuthViewController.m
//  SinaWeiBo
//
//  Created by WGP on 16/4/10.
//  Copyright © 2016年 WGP. All rights reserved.
//

#import "HMOAuthViewController.h"
#import "HMUserAccountViewModel.h"
#import "HMWelcomeViewController.h"
#import <SVProgressHUD.h>


@interface HMOAuthViewController ()<UIWebViewDelegate>

@property(nonatomic,strong)UIWebView *webView;

@end

@implementation HMOAuthViewController

-(void)loadView
{
    self.view = self.webView;
    self.webView.delegate = self;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupBarBtn];
    
    NSURL *url = [self getOAthURL];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
    
    [SVProgressHUD showWithStatus:@"正在拼命加载中..." maskType:SVProgressHUDMaskTypeGradient];
}


-(void)setupBarBtn
{
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"填充" style:UIBarButtonItemStylePlain target:self action:@selector(autoFill)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancel)];
}

#pragma mark - 私有方法
-(NSURL *)getOAthURL
{
    NSString *OAuthURLStr = OAuthURL;
    NSString *clientid = client_id;
    NSString *redirectURL = redirect_uri;
    
    NSString *urlStr = [NSString stringWithFormat:@"%@?client_id=%@&redirect_uri=%@",OAuthURLStr,clientid,redirectURL];
//    HMLog(@"%@",urlStr);
    
    return [NSURL URLWithString:urlStr];
}

#pragma mark - 导航条按钮点击事件
-(void)autoFill
{
    NSString *js = @"document.getElementById('userId').value = '18225529869';document.getElementById('passwd').value = 'abc18225529869'";
    [self.webView stringByEvaluatingJavaScriptFromString:js];
}

-(void)cancel
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 代理方法
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString *URLStr = request.URL.absoluteString;
//    HMLog(@"%@",URLStr);
    
//    授权取消的时候https://m.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330&from=844b&vit=fps
//    授权的确定的时候https://m.baidu.com/?code=5df17dba6a7d088c8f4ada0d4588f58e&from=844b&vit=fps
    
     NSString *redirectURL = redirect_uri;
    
    if([URLStr hasPrefix:redirectURL])
    {
        NSMutableString *query = [NSMutableString stringWithString:request.URL.query];
        NSString *codeStr = @"code=";
        if([query hasPrefix:codeStr])
        {
        [query replaceOccurrencesOfString:codeStr withString:@"" options:0 range:NSMakeRange(0, query.length)];
//            获得code
//            HMLog(@"%@",query);
            
//            开始加载AccessToken
            [[HMUserAccountViewModel sharedInstance] loadAccessToken:query loadAccessTokenFinished:^(NSError *error) {
               
                
//                加载AccessToken后关闭当前控制器
//               加载AccessToken完成
                if(error != nil)
                {
                    HMLog(@"获取AccessToken出错:%@",error);
                }
                
//                预先获取用户信息
                [[HMUserAccountViewModel sharedInstance] loadUserInfo:^(NSError *error) {
                    if(error != nil)
                    {
                        HMLog(@"加载用户信息出错:%@",error);
                        return ;
                    }
                }];
                
                [getApplicationDelegate switchRootViewController:[[HMWelcomeViewController alloc] init]];
                
            }];
        }
        else
        {
//            点击取消
            [self dismissViewControllerAnimated:YES completion:nil];
            
        }
        return NO;
    }
    else
    {
        return YES;
    }
    
}

-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    [SVProgressHUD dismiss];
}


-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    [SVProgressHUD dismiss];
//    HMLog(@"%@",error);
    if(error.code == 102)
    {
        return ;
    }
    [SVProgressHUD showErrorWithStatus:@"网络不给力!" maskType:SVProgressHUDMaskTypeGradient];
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 懒加载webView
-(UIWebView *)webView
{
    if(_webView==nil)
    {
        _webView = [[UIWebView alloc] init];
    }
    return _webView;
}

@end












